package edu.scau.cxq.gp.service.impl;

import edu.scau.cxq.gp.common.entity.CronEntity;
import edu.scau.cxq.gp.common.entity.MyFile;
import edu.scau.cxq.gp.common.utils.FileUtils;
import edu.scau.cxq.gp.dto.CronDTO;
import edu.scau.cxq.gp.service.MyFileService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Data
@ConfigurationProperties("file-utils")
public class MyFileServiceImpl implements MyFileService {


    @Autowired
    private FileUtils fileUtils;

    @Autowired
    private CronEntity cronEntity;

    private String shellCronFile;



    /**
     * 获取一个文件夹下的所有文件
     * @return
     */
    @Override
    public List<MyFile> getAllFile(String filepath) throws IOException {

        List<MyFile> myFiles = new ArrayList<>();

        List<String> allFile = fileUtils.getAllFile(filepath, false);

        for (String file : allFile) {
            MyFile myFile = new MyFile();
            myFile.setFilepath(file);
            myFile.setFileName(fileUtils.getFileName(file));
            myFile.setFileContent(fileUtils.getTemplateContent(file));

            myFiles.add(myFile);
        }

        return myFiles;
    }

    /**
     * 将单个文件保存（可用于新增和保存）
     * @param myFile
     * @return
     * @throws UnsupportedEncodingException
     */
    @Override
    public boolean saveFile(MyFile myFile) throws UnsupportedEncodingException {

        InputStream inputStream = fileUtils.changeStringIntoInputStream(myFile.getFileContent());

        return fileUtils.saveFile(myFile.getFilepath(), inputStream);
    }

    /**
     * 删除单个文件
     * @param myFile
     * @return
     */
    @Override
    public boolean delFile(MyFile myFile) {
        String filepath = myFile.getFilepath();
        return fileUtils.delFile(filepath);
    }

    /**
     * 获取单个文件的内容
     * @param filePath
     * @return
     */
    @Override
    public String getFileContent(String filePath) throws IOException {
        return fileUtils.getTemplateContent(filePath);
    }

    /**
     * 保存cron
     * @param cronDTO
     * @return
     */
    @Override
    public boolean saveCron(CronDTO cronDTO) {
        Map<String, List<String>> cronMap = cronEntity.getCronMap();
        Set<String> strings = cronMap.keySet();
        for (String string : strings) {
            if (string.contains(cronDTO.getFilepath())) {
                cronMap.put(string, cronDTO.getCron());
                break;
            }
        }

        Set<Map.Entry<String, List<String>>> entries = cronMap.entrySet();

        StringBuffer buffer = new StringBuffer();

        for (Map.Entry<String, List<String>> entry : entries) {
            List<String> value = entry.getValue();
            for (String s : value) {
                if (s.length() < 5) {
                    break;
                }
                buffer.append(s + "  " + entry.getKey() + '\n');
            }
        }

        String cron = buffer.toString();

        try {
            InputStream inputStream = fileUtils.changeStringIntoInputStream(cron);
            fileUtils.saveFile(shellCronFile, inputStream);
        } catch (UnsupportedEncodingException e) {
            return false;
        }

        try {
            Process process = Runtime.getRuntime()
                    .exec("crontab /root/cron/crontab.tmp");
            process.waitFor();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        cronEntity.setCronMap(cronMap);

        return true;
    }

    @Override
    public CronDTO getCron(String filepath) {
        CronDTO cronDTO = new CronDTO();
        cronDTO.setFilepath(filepath);

        Map<String, List<String>> cronMap = cronEntity.getCronMap();
        Set<String> strings = cronMap.keySet();

        for (String string : strings) {
            if (string.contains(filepath)) {
                cronDTO.setCron(cronMap.get(string));
                break;
            }
        }

        return cronDTO;
    }


}
